import {createRouter, createWebHashHistory} from "vue-router";
import {isLogin} from '../axios/API'
import {ElMessage} from "element-plus";
import TodoList from "../pages/TodoList.vue";
import Login from "../pages/Login.vue";
import MainContent from "../pages/MainContent.vue";
import UserInfo from "../pages/UserInfo.vue";
import Welcome from "../pages/Welcome.vue";
//创建并暴露一个路由器
const router = createRouter({
    history: createWebHashHistory(),
    routes: [
        {
            name: 'login',
            path: '/',
            component: Login
        },
        {
            name:'welcome',
            path:'/welcome',
            component:Welcome
        },
        {
            name: 'mainContent',
            path: '/main',
            component: MainContent,
            redirect:'/main/todo-list',
            children: [
                {
                    name: 'todoList',
                    path: 'todo-list',
                    component: TodoList,
                    meta: {
                        //是否需要鉴定权限
                        isAuth: true
                    }
                },{
                    name: 'userInfo',
                    path:'user-info',
                    component:UserInfo,
                    meta:{
                        isAuth: true
                    }
                }
            ],
        }
    ]
})

router.beforeEach((to, from, next) => {
    if (to.meta.isAuth) {
        //这里全局路由守卫中没法使用await，我试了不行，就只能这么写了
        isLogin().then(
            response => {
                const {data} = response
                if (data + '' === '200') {
                    next()
                } else {
                    ElMessage.error('未登录或登录已过期，请重新登录！')
                    next({name: 'login'})
                }
            },
            error => {
                console.log(error)
            }
        )
    }
    //这里遇到的问题记录一下，全局路由守卫中的逻辑一定要写完成，否则就会造成无论如何没法跳转的问题。
    else {
        next()
    }
})

export default router
